package function

import (
	"encoding/json"
	"gitee.com/moyrn/sa/engine"
	"gitee.com/moyrn/sa/store"
	"gitee.com/moyrn/sa/store/models"
	"io/ioutil"
	"net/http"
	"regexp"
)

var (
	domain    = "http://sannuo.test.cn"
	homeRegex = regexp.MustCompile(`<a class="thumbnail" href="([^"]*)" target="_self">`)
)

func Home(e *engine.Engine, task *models.Task) (newTasks []models.Task, err error) {
	request, err := http.NewRequest(http.MethodGet, task.Url, nil)
	if err != nil {
		store.Log.Info("Home NewRequest", err)
	}
	request.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.55")

	request.AddCookie(&http.Cookie{
		//Name:   "",
		//Value:  "",
		//Path:   "",
		//Domain: "",
	})

	resp, err := e.HttpClient.Do(request)
	if err != nil {
		store.Log.Info("Home Do", err)
	}
	defer resp.Body.Close()
	readAll, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		store.Log.Info("Home ReadAll", err)
	}

	subHomes := homeRegex.FindAllStringSubmatch(string(readAll), -1)
	for _, subHome := range subHomes {
		newTasks = append(newTasks, models.Task{
			Url:            domain + subHome[1],
			UniqueKey:      store.UniqueIndex(domain, subHome[1]),
			ParserFunction: "parserFunction_2",
			Status:         models.Unload,
		})
	}

	marshal, _ := json.Marshal(newTasks)

	task.Content = string(readAll)
	task.Remark = string(marshal)
	return newTasks, nil
}
